from PIL import Image, ImageDraw
import os
import sys
import math


def merge_images(circle_path, background_path, output_path, radius):
    """
    将圆形图片的中心圆形区域叠加到背景图片的中心
    
    :param circle_path: 圆形图片路径
    :param background_path: 背景图片路径
    :param output_path: 输出图片路径
    :param radius: 可选参数，指定圆形半径（像素）。若为None则自动取内切圆
    """
    # 打开两张图片并确保为RGBA模式
    circle_img = Image.open(circle_path).convert("RGBA")
    background_img = Image.open(background_path).convert("RGBA")
    
    # 获取圆形图片尺寸
    circle_width, circle_height = circle_img.size
    
    # 计算默认半径（最小边的一半）
    if radius is None:
        radius = min(circle_width, circle_height) // 2
    else:
        # 确保半径不超过图片边界
        radius = min(radius, circle_width//2, circle_height//2)
    
    # 计算圆心坐标
    center_x, center_y = circle_width // 2, circle_height // 2
    
    # 创建圆形遮罩
    mask = Image.new("L", (circle_width, circle_height), 0)  # 全黑遮罩
    draw = ImageDraw.Draw(mask)
    draw.ellipse(
        (center_x - radius, center_y - radius, 
         center_x + radius, center_y + radius),
        fill=255
    )
    
    # 应用圆形遮罩
    circle_img.putalpha(mask)
    
    # 计算在背景上的粘贴位置（居中）
    bg_width, bg_height = background_img.size
    position = (
        (bg_width - circle_width) // 2,
        (bg_height - circle_height) // 2
    )
    
    # 合成图片
    result = background_img.copy()
    result.paste(circle_img, position, circle_img)
    
    # 保存结果
    result.save(output_path, "PNG")
    print(f"合成图片已保存至: {output_path} (半径: {radius}px)")

# 使用示例
if __name__ == "__main__":
    circle_path = sys.argv[1]
    background_path = sys.argv[2]
    background_dir = os.path.dirname(background_path)
    background_name = os.path.basename(background_path)


    output_path = os.path.join(background_dir, background_name.split('.')[0] + '_merged.png')
    if len(sys.argv) > 3:
        radius = int(sys.argv[3])
    else: 
        radius = 704

    merge_images(
        circle_path= circle_path,
        background_path= background_path,
        output_path=output_path,
        radius=radius      

    )